//
//  JsonData.m
//
//  Created by Kevin Wong on 2012-12-02.
//  Copyright (c) 2012 Kevin Wong. All rights reserved.
//

#import "JsonData.h"

@interface JsonData ()
@end

@implementation JsonData
//{
//    NSMutableArray * _objects;
//}

@synthesize teamArray;

- (id)init
{
    self = [super init];
    return self;
}

- (NSString*) characterDataPath
{
    NSString * documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    
    return [documentsPath stringByAppendingPathComponent:@"Characters.keyed"];
}

- (NSURL*)buildTeamURL:(NSString*)team:(NSString*)season {
    
    NSLog(@"Building url for team: %@", team);
    
    // Build the string with the team filter
    NSString *urlString = [@"http://api.sportsdatabase.com/nhl/query.json?sdql=date%2Co%3Ateam%2Cgoals%2Co%3Agoals%2Csite%2Cshots+on+goal%2Co%3Ashots+on+goal%2Cfaceoffs+won%2Co%3Afaceoffs+won%40team%3D" stringByAppendingString:team];
    
    // Add the season query
    urlString = [urlString stringByAppendingString:@"+and+season%3D"];
    
    // Applying the season filter value
    urlString = [urlString stringByAppendingString:season];
    
    // Add the api key
    urlString = [urlString stringByAppendingString:@"&output=json&api_key=kw48158"];
    
    NSURL * url = [NSURL URLWithString:urlString];
    
    NSLog(@"URL: %@", url);
    
    return url;
}

- (NSURL*)buildPlayerURL:(NSString*) playerName:(NSString*) season
{
    
    //NSString *SDQL = [NSString stringWithFormat:@"date,full name,wins,losses,goals,assists,points,streak@team = %@ and date>=20050101",TeamName];
    NSString *P2 = @"%2";
    NSString *P3 = @"%3";
    NSString *P40 = @"%40";
    
    
    NSString *urlString = [NSString stringWithFormat:@"http://api.sportsdatabase.com/nhl/query.json?sdql=date%@C%@%@Anumber%@C%@%@Aposition%@C%@%@Agoals%@C%@%@Aassists%@C%@%@Apoints%@C%@%@Apenalty+minutes%@C%@%@Aplus+minus%@C%@%@Ashots+on+goal%@C%@%@Afaceoffs+won%@season%@D%@+and+%@%@Ap%@Aname+%@D+%@&output=json&api_key=kw48158",P2,playerName,P3,P2,playerName,P3,P2,playerName,P3,P2,playerName,P3,P2,playerName,P3,P2,playerName,P3,P2,playerName,P3,P2,playerName,P3,P2,playerName,P3,P40,P3,season,playerName,P3,P3,P3,playerName];
    
    NSURL * url = [NSURL URLWithString:urlString];
    
    NSLog(@"%@", url);
    return url;
}

- (NSMutableDictionary*)executeQuery:(NSURL*) url
{
    //team,date,season,opp,site,position,goals,assists,points@Jarome:points>=0
    
    __block NSMutableDictionary *dataDic;
    
    NSError *error = nil;
    NSURLResponse *response = nil;
    NSURLRequest * urlRequest = [NSURLRequest requestWithURL:url]; // CRASHES
    
    NSData *data = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];
    
    // was there a problem loading the URL?
    if(error)
    {
        // show an alert, and abort
        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"There was an error loading the requested URL." delegate:nil cancelButtonTitle:@"Okay" otherButtonTitles:nil];
        
        [alert show];
        
    }
    
    // http://en.wikipedia.org/wiki/MIME
    if([response.MIMEType isEqualToString:@"application/json"] ||
       [response.MIMEType isEqualToString:@"text/plain"] ||
       [response.MIMEType isEqualToString:@"text/html"] )
    {
        NSString * contents = [[NSString alloc] initWithBytes:data.bytes length:data.length encoding:NSUTF8StringEncoding];
        
        // parse out the json_callback padding
        NSRange rangeOfCallBack = [contents rangeOfString:@"json_callback("];
        
        if( rangeOfCallBack.location == NSNotFound || rangeOfCallBack.location != 0 )
        {
            // cannot find the padding
            NSLog(@"ERROR with the json received.");
        }
        
        NSString * json = [contents substringFromIndex:rangeOfCallBack.length];
        json = [json substringToIndex:json.length - 3];
        json = [json stringByReplacingOccurrencesOfString:@"'" withString:@"\""];
        NSData * jsonData = [json dataUsingEncoding:NSUTF8StringEncoding];
        
        NSError * jsonError = nil;
        
        // Contains a dictionary of the json object
        NSDictionary * jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&jsonError];
        
        
        NSArray *headers = [jsonObject objectForKey:@"headers"];
        
        // groups returns an array of dictionaries, where the first element is an another dictionary
        NSArray *columns = [[[jsonObject objectForKey:@"groups"] objectAtIndex:0] objectForKey:@"columns"];
        
        
        //NSMutableDictionary *playerData = [NSMutableDictionary dictionary];
        dataDic = [NSMutableDictionary dictionary];
        
        
        // Populates the playerData dictionary
        for (int i=0;i<headers.count;i++) {
            NSString *propertyName = [headers objectAtIndex:i];
            
            id value = [columns objectAtIndex:i];
            dataDic[propertyName] = value;
        }
        
        //NSLog(@"team: %@", playerData[@"o:team"]);
    }
    return dataDic;
}

//- (void) saveData
//{
//    // we need to save our data here using a NSKeyedArchiver instance
//    [NSKeyedArchiver archiveRootObject:_objects toFile:self.characterDataPath];
//}
@end
